﻿using System;
using System.Windows.Forms;

namespace SyringeControl.Factories
{
    /// <summary>
    /// Implementation of <see cref="IControlFactory"/> interface using <see cref="System.Activator"/> for creating controls
    /// </summary>
    public class ActivatorControlFactory : IControlFactory
    {
        #region Члены IControlFactory
        /// <summary>
        /// Checks whether <see cref="IControlFactory"/> can create an instance of given type
        /// </summary>
        /// <param name="type">type, instance of which needs to be created</param>
        /// <returns>true if this factory can create instance of given type</returns>
        /// <remarks>Type can be instatiated if 
        ///   - it is public and not abstract;
        ///   - it has public default constructor;</remarks>
        public bool IsValid(Type type)
        {
            return !type.IsAbstract && type.GetConstructor(new Type[0]) != null;
        }
        /// <summary>
        /// Creates instance of type <paramref name="type"/>.
        /// </summary>
        /// <param name="type">type, instance of which needs to be created</param>
        /// <returns>instance of given control type.</returns>
        /// <exception cref="ArgumentException"> if <paramref name="type"/> cannot be instantiated by this factory</exception>
        public Control Create(Type type)
        {
            if (type == null)
                return null;
            if (!IsValid(type))
                throw new ArgumentException("type "+type+" cannot be instantiated by this factory", "type");
            return (Control)Activator.CreateInstance(type);
        }

        #endregion
    }
}
